﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using QxFramework.Core;
using GameMap;
using Unity.Collections;
namespace GameControl
{
    public class ItemInstantiateManager : LogicModuleBase,IItemInstantiateManager
    {
        private Dictionary<string, GameObject> _itemDic = new Dictionary<string, GameObject>();
        public Dictionary<string, ItemField> _itemFieldDic = new Dictionary<string, ItemField>();
        //  private List<Item> _itemList = new List<Item>();
        GameObject map;
    //    public delegate void InstantiateManagerLoadFinish();
        public Item CreateItem(ItemField info,object args=null,Transform fa=null)
        {
            if (fa == null) fa = map.transform;
            var obj = ResourceManager.Instance.Instantiate(_itemDic[info.ItemName.Split('_')[0]],fa);
        //    obj.layer = _itemDic[info.ItemName.Split('_')[0]].layer;
            var item = obj.GetComponent<Item>();
            item.name = info.ItemName;
            item.OnAwake();
            item.ItemFieldSetting = info;

            item.HaveDestoryEffects = true;
            //   rigid.GetComponent<>
            //   item.ItemFieldSetting = info;
            if (info is CombinableItemField)
            {
                var rigid = CreateItemRigid();
                item.transform.position = (info as CombinableItemField).Position;
                rigid.transform.position = (info as CombinableItemField).Position;
                item.transform.SetParent(rigid.transform);
                rigid.GetComponent<ItemRigid>().SetRigidInfo();
                rigid.ChangeLayer(_itemDic[info.ItemName.Split('_')[0]].layer);
            }
            else
            {
                obj.ChangeLayer(_itemDic[info.ItemName.Split('_')[0]].layer);
            }
            item.GetComponent<Item>().DownloadInstanceField(info);

            if (item is CombinableItem)
            {
                var funcs = (item as CombinableItem).FuncList;
                foreach (var x in funcs)
                {
                    x.OnStart();
                }
            }
            //      _itemList.Add(item);
            return item;
        }
        int instanceCnt = 0;
        public ItemField CreatItemField(string name,Item existItem = null)
        {
            ItemField tp=null;
           
            try
            {

                if (existItem == null)
                {

                    tp= UnsafeTool.DeepCopyByJson(_itemDic[name].GetComponent<Item>().ItemFieldSetting);
           //         tp = UnsafeTool.DeepCopy<ItemField>(_itemDic[name].GetComponent<Item>().ItemFieldSetting);
                }
                else
                {
                    if (string.IsNullOrEmpty(existItem.ItemFieldSetting.ItemName))
                    {
                        existItem.ItemFieldSetting.ItemName = name;
                    }
                     tp = existItem.ItemFieldSetting;
                    name = existItem.ItemFieldSetting.ItemName.Split('_')[0];
                }
                if (string.IsNullOrEmpty(tp.ItemName))
                {
                    tp.ItemName = existItem.name.Split(' ')[0].Split('(')[0];
                }
                
                tp.ItemName = tp.ItemName + "_" + (++instanceCnt);
                GameManager.Get<IItemFuncManager>().AddFuncField(_itemDic[name].GetComponent<Item>(), tp.ItemName);
                _itemFieldDic[tp.ItemName] = tp;
            }
            catch(KeyNotFoundException e)
            {
                return null;
            }
            catch(System.Exception e)
            {
                Debug.LogError(e);
            }
            return tp;
        }
        public ItemField GetItemFieldByName(string name)
        {
            if (_itemFieldDic.ContainsKey(name) == false) return null;
            return _itemFieldDic[name];
        }
        public override void Init(object args)
        {
            base.Init(args);
            var list=Resources.LoadAll<GameObject>("Prefabs/Item/");
            foreach(var x in list)
            {
                _itemDic[x.name] = x.gameObject;
                x.GetComponent<Item>().ItemFieldSetting.ItemName = x.name;
                
            }
            var tp = new List<ItemField>(GameMapManager.Get<IMapManager>().SceneItems);
            tp.AddRange(GameMapManager.Get<IBagManager>().ItemsInBench);
            tp.AddRange(GameMapManager.Get<IBagManager>().ItemsInBag);
            foreach(var x in tp)
            {
                _itemFieldDic[x.ItemName]=x;
                instanceCnt = Mathf.Max(instanceCnt, int.Parse(x.ItemName.Split('_')[1]));
            }
            map = GameObject.Find("Map");

            if (map == null)
            {
                map = new GameObject();
                map.name = "Map";
            }
        }

        public void DestoryItem(Item item)
        {
            if (item == null)
            {
                return;
            }
            if(item is CombinableItem)
            {
                var funcs = (item as CombinableItem).FuncList;
                foreach(var x in funcs)
                {
                    x.OnDestory();
                }
            }
            if (_itemFieldDic.ContainsKey(item.ItemFieldSetting.ItemName)==false)
            {
                if (GameManager.Instance.OnEndLevel)
                {
             //       item.DestoryEffect();
                }
                else
                {
                    item.OnRealDestory();

                }
            }
            item.OnPreferenceDestory();
            ObjectPool.Recycle(item.gameObject);
        }

        public void DestoryItemField(string name)
        {
            GameCombine.CombineManager.Get<GameCombine.IItemCombineManager>().RemoveJointAbout(name);
            GameManager.Get<IItemFuncManager>().RemoveFuncAbout(name);
            _itemFieldDic.Remove(name);
            if (GameManager.Instance.OnEndLevel == false)
            {
                Launcher.Instance.StartCoroutine(WaitToRemove(name));

            }
        }
        IEnumerator WaitToRemove(string name)
        {
            yield return new WaitForSeconds(Time.fixedDeltaTime * 3);
            GameManager.Get<IItemHealthManager>().IgnorePairs.RemoveAll(s => s.Item1 == name || s.Item2 == name);

        }
        public Item GetItemSettingByName(string name)
        {
            return _itemDic[name.Split('_')[0]].GetComponent<Item>();
        }

        public GameObject CreateItemRigid()
        {
            var rigid = ResourceManager.Instance.Instantiate("Prefabs/Component/Rigid", map.transform);
            rigid.transform.position = Vector3.zero;
            var body = rigid.GetComponent<Rigidbody2D>();
            body.velocity = Vector3.zero;
            body.angularVelocity = 0f;
            rigid.transform.eulerAngles = Vector3.zero;
            rigid.transform.GetComponent<Rigidbody2D>().freezeRotation = false;
            rigid.transform.GetComponent<Rigidbody2D>().gravityScale = 1;
            return rigid;
        }
    }
    interface IItemInstantiateManager
    {
        /// <summary>
        /// 不要随意调用
        /// </summary>
        /// <param name="info"></param>
        /// <param name="args"></param>
        /// <param name="parent"></param>
        /// <returns></returns>
        Item CreateItem(ItemField info, object args=null, Transform parent=null);
        ItemField CreatItemField(string name,Item existItem=null);
        ItemField GetItemFieldByName(string name);
        Item GetItemSettingByName(string name);
        void DestoryItem(Item item);
        void DestoryItemField(string name);

      
        GameObject CreateItemRigid();

    }
}